<?php
/**
 * Created by PhpStorm.
 * User: zhenl
 * Date: 2022/10/28
 * Time: 15:28
 */

namespace app\api\controller;


use app\BaseController;
use app\Request;
use common\Constant;
use common\models\OrderDetailModel;
use common\models\OrderModel;
use common\models\ProductModel;
use common\models\UserModel;
use think\facade\Db;
use think\helper\Str;

class Order extends BaseController
{

    public function create(Request $request)
    {
        // 获取用户身份
        $user_id = $request->header('user');
        $user_model = UserModel::find($user_id);

        $post = $request->post();
        $quantity = $post['quantity'];
        // 查找商品
        $product_model = ProductModel::find($post['product_id']);

        Db::startTrans();
        $order_model = OrderModel::create([
            'order_no' => get_trade_no(),
            'user_id' => $user_model->id,
            'address_id' => $post['address_id'],
            'consignee' => '',
            'mobile' => '',
            'province' => '',
            'city' => '',
            'area' => '',
            'district' => '',
            'address' => '',
            'order_total' => bcmul($product_model->sell_price, $quantity, 2),
            'order_amount' => bcmul($product_model->sell_price, $quantity, 2),
            'discount' => 0,
            'voucher_id' => $post['voucher_id'],
            'status' => Constant::ORDER_STATUS_CREATE,
            'delivery_status' => Constant::STATUS_NO,
        ]);

        OrderDetailModel::create([
            'product_id' => $product_model->id,
            'order_id' => $order_model->order_id,
            'spec_id' => 0,
            'name' => $product_model->name,
            'image' => $product_model->main_image,
            'sell_price' => $product_model->sell_price,
            'raw_price' => $product_model->raw_price,
            'quantity' => $quantity,
            'discount' => 0,
        ]);
        Db::commit();
//        Db::rollBack();

        return $this->success($order_model);
    }
}